import axios from "axios";
import { ElLoading, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import router from "@/router";

let loadingInstance = null

const instance = axios.create({
    baseURL: '/dev-api',
    timeout:5000
})

const RESPONSE_CODE = {
  success: 1000,
  reLogin: 3001
}

instance.interceptors.request.use(function (config) {
  // 显示loading
  loadingInstance = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  // 获取 token
  const userStore = useUserStore()
  const token = userStore.token
  
  // 如果有 token，添加到请求头
  if (token) {
    config.headers.Authorization = token
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  loadingInstance?.close()
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 关闭loading
  console.log("response:",response.data)

  loadingInstance?.close()
  const { data: resp } = response
  const { code, data, msg } = resp
  if (code === RESPONSE_CODE.success || data != null) {
    return resp
  }
  return Promise.reject(new Error(msg));
}, function (error) {
  // 关闭loading
  loadingInstance?.close()
  
  // 处理 401 未授权错误
  if (error.response?.status === 401) {
    ElMessage.error("登录状态已过期，请重新登录")
    const userStore = useUserStore()
    userStore.clearToken()
    router.push("/login")
  } else {
    // 处理其他错误，包括超时错误
    ElMessage.error(error.message || '请求失败')
  }
  
  return Promise.reject(error);
})

export default instance